package com.example.doctor.jpa;

import com.example.common.entity.RxMain;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface RxMainRepository extends JpaRepository<RxMain,String> {

    @Query(value = "SELECT * FROM order_rx_main WHERE order_no_nvarchar =:orderNo ORDER BY create_time_datetime DESC LIMIT 1",nativeQuery = true)
    RxMain findByOrderNOByOne(@Param("orderNo") String orderNo);

    @Query(value = "SELECT * FROM order_rx_main WHERE order_no_nvarchar =:orderNo and is_trial_pharm_ca_bit = true ORDER BY create_time_datetime DESC LIMIT 1",nativeQuery = true)
    RxMain findLastOrder(@Param("orderNo") String orderNo);

    List<RxMain> findByOrderNOAndIsTrialPharmCa(String orderNO,Boolean isTrialPharmCa);

    @Query(value = "SELECT * FROM order_rx_main WHERE order_no_nvarchar =:orderNO AND system_status_tinyint=2",nativeQuery = true)
    List<RxMain> findByOrderNOAndSystem(@Param("orderNO") String orderNO);

    @Query(value = "SELECT * FROM order_rx_main WHERE order_no_nvarchar =:orderNO AND system_status_tinyint=2",nativeQuery = true)
    List<RxMain> findListByOrderNO(@Param("orderNO") String orderNO);


    @Query(value = "select b.* from order_main a"
    +" inner join order_rx_main b on a.order_no_nvarchar = b.order_no_nvarchar"
    +" where a.pid_bigint = :pid and a.a_type_int = 10 and a.oc_status_tinyint != 0 and a.system_status_tinyint = 2"
            +" and b.system_status_tinyint=2 and b.is_trial_pharm_ca_bit = true"
    +" order by b.create_time_datetime desc"
    +" limit 1",nativeQuery = true)
    RxMain findByLastOne(@Param("pid") long pid);

    @Query(value = "select recipe_doc_signature_xml_nvarchar from order_rx_main where rx_order_no_nvarchar = ?1", nativeQuery = true)
    String getXml(String orderId);

    @Query(value = "select ca_code from doctor_base_info where phone = ?1", nativeQuery = true)
    String getCaMessage(String phone);

    @Modifying
    @Transactional
    @Query(value = "update order_rx_main set recipe_doc_signcertificate_nvarchar = ?1,  recipe_doc_signature_value_nvarchar = ?2 where rx_order_nO_nvarchar = ?3", nativeQuery = true)
    int updateSigJob(String signCert, String signResult, String orderId);

    @Modifying
    @Transactional
    @Query(value = "update order_rx_main set is_recipe_doc_ca_bit = 1, recipe_doc_time_stamp_nvarchar = ?2 where rx_order_nO_nvarchar = ?1", nativeQuery = true)
    int updatVerif(String orderId, String time);

    @Modifying
    @Transactional
    @Query(value = "update order_rx_main set recipe_doc_time_stamp_nvarchar = ?2 where rx_order_nO_nvarchar = ?1", nativeQuery = true)
    int updatTime(String orderId, String time);
}
